/**
 * @file Log.cpp
 * @brief 日志记录类
 * @author enemy1205 (enemy1205@qq.com)
 * @date 2021-8-17
 */
# include "Log.h"
#include <utility>
string currTime(){
    // 获取当前时间，并规范表示
    char tmp[64];
    time_t ptime;
    time(&ptime);
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", localtime(&ptime));//格式化结构ptime表示的时间
    return tmp;
}

/**
 * @brief 默认构造函数
 */
Logger::Logger() {
    this->target = file;
    this->level = info;
    this->outfile.open(path, ios::out | ios::app);
}

/**
 * @brief 指定构造函数
 * @param target 日志输出目标
 * @param level 构造时日志等级
 */
Logger::Logger(log_target target, log_level level) {
    this->target = target;
    this->level = level;
    if (target != terminal) this->outfile.open(path, ios::out | ios::app);   // 打开输出文件
}

/**
 * @brief 输出控制
 * @param text 记录文本
 * @param act_level 实际调用时日志等级
 */
void Logger::output(string text, log_level act_level) {
    string prefix;
    if (act_level == debug) prefix = "[DEBUG]  ";
    else if (act_level == info) prefix = "[INFO]   ";
    else if (act_level == warning) prefix = "[WARNING]";
    else if (act_level == error) prefix = "[ERROR]  ";
    else prefix = "";
    prefix += " ";
    string output_content = prefix + currTime() + " : " + text + "\n";
    if (this->level == act_level && this->target != file) {
        // 当前等级设定的等级才会显示在终端，且不能是只文件模式
        cout << output_content;
    }
    if (this->target != terminal)
        outfile << output_content;
}

//-------------------避免构造实例化多个对象------------------------
void Logger::DEBUG(string text) {
    this->output(move(text), debug);
}

void Logger::INFO(string text) {
    this->output(move(text), info);
}

void Logger::WARNING(string text) {
    this->output(move(text), warning);
}

void Logger::ERROR(string text) {
    this->output(move(text), error);
}
